﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fluent.Logging;

namespace Fluent.Exceptions
{
    public class ExceptionManager
    {
        private int triedCount = 0;

        private List<Exception> ExContainer { get; set; }

        public void Add(Exception ex)
        {
            this.ExContainer.Add(ex);
        }

        public bool Excute(Action testSteps)
        {
            bool excuteResult = true;
            try
            {
                testSteps();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Catch Exceptions while doing action.");
                excuteResult = false;
            }

            return excuteResult;
        }

        public bool Catch(Action action, int tryCount = 1, Action resetAction = null)
        {
            bool isCatchedException = false;

            try
            {
                this.triedCount++;
                action();
            }
            catch (Exception ex)
            {
                isCatchedException = true;
                Log.Error(ex, "Catch Exceptions while doing action.");
                if (this.triedCount < tryCount)
                {
                    if (resetAction != null)
                    {
                        resetAction();
                    }

                    isCatchedException = this.Catch(action, tryCount, resetAction);
                }
            }

            return isCatchedException;
        }

        public bool Catch<TException>(Action action, int tryCount = 1, Action resetAction = null)
            where TException : Exception
        {
            bool isCatchedException = false;

            try
            {
                action();
            }
            catch (TException ex)
            {
                Log.Error(ex, "Catch Exceptions while doing action.");
                isCatchedException = true;
            }

            return !isCatchedException;
        }
    }
}
